package com.shenhan.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * <br>
 *
 * <p>- <br>
 *
 * @author shenhan
 * @version 1.0
 * @date: 2022/5/16 17:59
 * @description:
 */
public class NioDiscardServer {

  public static void startServer() throws IOException {
    Selector selector = Selector.open();
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.bind(new InetSocketAddress(18899));
    System.out.println("服务器启动成功");
    // 将通道注册的“接收新连接”IO事件注册到选择器上
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (selector.select() > 0) {
      Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
      while (iterator.hasNext()) {
        SelectionKey selectedKey = iterator.next();
        if (selectedKey.isAcceptable()) {
          SocketChannel socketChannel = serverSocketChannel.accept();
          socketChannel.configureBlocking(false);
          socketChannel.register(selector, SelectionKey.OP_READ);
        } else if (selectedKey.isReadable()) {
          SocketChannel socketChannel = (SocketChannel) selectedKey.channel();
        }
      }
    }
  }
}
